package com.timothy.android;

import java.util.ArrayList;
import java.util.List;

import com.timothy.android.util.NumberUtil;
import com.timothy.answer.BaseAnswer;
import com.timothy.answer.STTwoButtonAlphaAnswer;
import com.timothy.answer.Vote;
import com.timothy.chart.CanvasSetting;
import com.timothy.chart.Bar2D;
import com.timothy.question.BaseQuestion;
import com.timothy.question.TypeBean1;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;

public class Bar2DAnswerActivity extends BaseActivity implements OnDoubleTapListener, OnGestureListener,OnTouchListener{
	private final static String LOG_TAG = "Bar2DAnswerActivity";
	private TypeBean1 bean;
	private int totalVotes = 0;
	
	List<Bar2D> barList;
	List<BaseAnswer> answers;
	
	GestureDetector mGestureDetector;
	
	STTwoButtonAlphaAnswer answer = null;
	List<Vote> voteList = null;
	BaseQuestion question = null;
	
	String questionName = null;
	String vote1 = null;
	String vote2 = null;
	String vote3 = null;
	String choice1 = null;
	String choice2 = null;
	String choice3 = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		VerticalBar2DView view = new VerticalBar2DView(this);
		view.setOnTouchListener(this);
		view.setLongClickable(true);
		setContentView(view);
		
		bean = TypeBean1.getMockInstance();
		
		//mock information
		Bundle bundle = this.getIntent().getExtras();
		questionName = bundle.getString("questionName");
		vote1 = bundle.getString("vote1");
		vote2 = bundle.getString("vote2");
		vote3 = bundle.getString("vote3");
		choice1 = bundle.getString("choice1");
		choice2 = bundle.getString("choice2");
		choice3 = bundle.getString("choice3");
		
		answer = new STTwoButtonAlphaAnswer();
		voteList = new ArrayList<Vote>();
		question = new BaseQuestion(1,questionName);
//		BaseAnswer answer1 = new BaseAnswer(question);
		
		//获取图形数据
		barList = new ArrayList<Bar2D>();
		Bar2D bar1=new Bar2D(0,Integer.parseInt(vote1),choice1, 1,Color.RED);
		totalVotes+=bar1.getVotes();
		barList.add(bar1);
		Bar2D bar2=new Bar2D(1,Integer.parseInt(vote2),choice2,1,Color.GREEN);
		totalVotes+=bar2.getVotes();
		barList.add(bar2);
		if(choice3!=null&&!"".equals(choice3)){
			Bar2D bar3=new Bar2D(2,Integer.parseInt(vote3),choice3,1,Color.BLUE);
			totalVotes+=bar3.getVotes();
			barList.add(bar3);			
		}

		
		Log.i(LOG_TAG, "VerticalBar2DView:totalVotes:"+totalVotes);
		mGestureDetector = new GestureDetector((OnGestureListener) this); 
	}
	
/*	@Override
	public boolean onTouchEvent(MotionEvent event) {
        if(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE == getRequestedOrientation()){
    		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    		setContentView(new VerticalBar2DView(this));        	
        }else{
    		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    		setContentView(new HorizontalBar2DView(this));          	
        }
		return super.onTouchEvent(event);
	}*/
	
	class VerticalBar2DView extends SurfaceView implements SurfaceHolder.Callback {
		private SurfaceHolder mHolder;
		private Canvas canvas;

		public VerticalBar2DView(Context context) {
			super(context);
			mHolder = getHolder();
			mHolder.addCallback(this);// 设置Surface生命周期回调
		}

		public void surfaceCreated(SurfaceHolder holder) {
			canvas = mHolder.lockCanvas();// 获得画布
			
			int canvasHeight = canvas.getHeight();
			int canvasWidth = canvas.getWidth();
			Log.i(LOG_TAG, "VerticalBar2DView:Canvas Height:"+canvasHeight);
			Log.i(LOG_TAG, "VerticalBar2DView:Canvas Width:"+canvasWidth);
			
			CanvasSetting setting = new CanvasSetting(canvasHeight,canvasWidth,Color.BLACK,1);
			
			//write question
			canvas.drawColor(setting.getBgColor());// 设置画布背景为黑色
			Paint mPaint = new Paint();
			mPaint.setColor(Color.WHITE);		
			mPaint.setTextSize(25);
			canvas.drawText(question.getQuestionName(), 50, 30, mPaint); 
			canvas.save();
			
			//根据图形个数既图形间距计算出图形宽度
			Log.i(LOG_TAG, "VerticalBar2DView:spaceInCharts:"+setting.getSpaceInCylis());
			int canvasNoMarginWidth = canvasWidth - setting.getLeftMargin() - setting.getRightMargin();
			double barWidthInclSpace = (canvasNoMarginWidth * 1.0)/barList.size();
			int barWidth = (int)(barWidthInclSpace*0.9);
			setting.setSpaceInCylis((int)(barWidthInclSpace-barWidth));
			Log.i(LOG_TAG, "VerticalBar2DView:barWidth:"+barWidth);
			
			for(int i=0;i<barList.size();i++){
				Bar2D bar2D = barList.get(i);
				
				//根据总票数，计算出比例，再乘以画布的高度
				
				int votes = bar2D.getVotes();
				double votesShare = (1.0* bar2D.getVotes())/totalVotes;
				int barHeigth = (int) (votesShare * canvasHeight);
				
				Log.i(LOG_TAG, "VerticalBar2DView:barHeigth:"+barHeigth);
				Log.i(LOG_TAG, "VerticalBar2DView:votes:"+votes);
				Log.i(LOG_TAG, "VerticalBar2DView:votesShare:"+votesShare);
				
				String answerText = null; 
				switch (bar2D.getAnswerType()){
				    case 0:answerText =  String.valueOf(votes);break; 
				    case 1:answerText =  NumberUtil.formatData2Deci(votesShare*100)+"%";break;
				    case 2:answerText =  String.valueOf(votes)+":"+NumberUtil.formatData2Deci(votesShare*100)+"%";break;
				}
				
				Log.i(LOG_TAG, "VerticalBar2DView:answerText:"+answerText);
				
				int tlX = (int) (setting.getLeftMargin()+ i * (barWidth + setting.getSpaceInCylis()));
				int tlY =  canvasHeight - setting.getBottomMargin() - barHeigth;
				int brX = tlX + barWidth;
				int brY = canvasHeight - setting.getBottomMargin();
				
				Log.i(LOG_TAG, "VerticalBar2DView:tlX,tlY,brX,brY="+tlX+","+tlY+","+brX+","+brY+",");
				

				mPaint.setColor(bar2D.getFullColor());
				canvas.drawRect(tlX,tlY,brX,brY, mPaint);
				canvas.save();
				
				mPaint.setTextSize(20);
				canvas.drawText(answerText, tlX, tlY-20, mPaint);
				canvas.drawText(bar2D.getChoiceText(), tlX, canvasHeight-20, mPaint);
				canvas.save();
			}

			canvas.restore();
			mHolder.unlockCanvasAndPost(canvas);// 完成绘图后解锁递交画布视图
		}
		
		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
		}
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			
		}
	}
	
	class HorizontalBar2DView extends SurfaceView implements SurfaceHolder.Callback {
		private SurfaceHolder mHolder;
		private Canvas canvas;

		public HorizontalBar2DView(Context context) {
			super(context);
			mHolder = getHolder();
			mHolder.addCallback(this);// 设置Surface生命周期回调
		}

		public void surfaceCreated(SurfaceHolder holder) {
			canvas = mHolder.lockCanvas();// 获得画布
			
			int canvasHeight = canvas.getHeight();
			int canvasWidth = canvas.getWidth();
			Log.i(LOG_TAG, "HorizontalBar2DView:Canvas Height:"+canvasHeight);
			Log.i(LOG_TAG, "HorizontalBar2DView:Canvas Width:"+canvasWidth);
			
			CanvasSetting setting = new CanvasSetting(canvasHeight,canvasWidth,Color.BLACK,2);
			
			//write question
			canvas.drawColor(setting.getBgColor());// 设置画布背景为黑色
			Paint mPaint = new Paint();
			mPaint.setColor(Color.WHITE);		
			mPaint.setTextSize(25);
			canvas.drawText(bean.getQuestion(),canvasWidth/4,30, mPaint); 
			canvas.save();
			
			//根据图形个数既图形间距计算出图形宽度
			Log.i(LOG_TAG, "HorizontalBar2DView:spaceInCharts:"+setting.getSpaceInCylis());
//			int barWidth = (canvasWidth - setting.getLeftMargin() - setting.getRightMargin())/barList.size() - (int) setting.getSpaceInCylis();
			int barHeight = (canvasHeight - setting.getTopMargin() - setting.getBottomMargin())/barList.size() - (int) setting.getSpaceInCylis();
			Log.i(LOG_TAG, "HorizontalBar2DView:barHeight:"+barHeight);
			
			for(int i=0;i<barList.size();i++){
				Bar2D bar2D = barList.get(i);
				
				//根据总票数，计算出比例，再乘以画布的高度
				
				int votes = bar2D.getVotes();
				double votesShare = (1.0* bar2D.getVotes())/totalVotes;
//				int barHeigth = (int) (votesShare * canvasHeight);
				int barWidth = (int) (votesShare * canvasWidth);
				
				Log.i(LOG_TAG, "HorizontalBar2DView:barWidth:"+barWidth);
				Log.i(LOG_TAG, "HorizontalBar2DView:votes:"+votes);
				Log.i(LOG_TAG, "HorizontalBar2DView:votesShare:"+votesShare);
				
				String answerText = null; 
				switch (bar2D.getAnswerType()){
				    case 0:answerText =  String.valueOf(votes);break; 
				    case 1:answerText =  String.valueOf(votesShare*100)+"%";break;
				    case 2:answerText =  String.valueOf(votes)+":"+String.valueOf(votesShare*100)+"%";break;
				}
				
				Log.i(LOG_TAG, "HorizontalBar2DView:answerText:"+answerText);
				
				int tlX = setting.getLeftMargin();
				int tlY = setting.getTopMargin()+ (int)(i*(barHeight + setting.getSpaceInCylis()));
				int brX = tlX + barWidth;
				int brY = tlY + barHeight;
				
				Log.i(LOG_TAG, "HorizontalBar2DView:tlX,tlY,brX,brY="+tlX+","+tlY+","+brX+","+brY+",");
				
				mPaint.setTextSize(25);
				canvas.drawText(answerText, tlX + barWidth+10, tlY+barHeight/2, mPaint);
				
				canvas.drawText(bar2D.getChoiceText(),10, tlY+barHeight/2, mPaint);
				
				mPaint.setColor(bar2D.getFullColor());
				canvas.drawRect(tlX,tlY,brX,brY, mPaint);
				
				canvas.save();
			}

			canvas.restore();
			mHolder.unlockCanvasAndPost(canvas);// 完成绘图后解锁递交画布视图
		}
		
		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
		}
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			
		}
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

    private int verticalMinDistance = 20;
    private int minVelocity         = 0;

    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {
        	Bundle bundle = new Bundle();
			Intent intent = new Intent();
		    intent.setClass(this, CylinderAnswerActivity.class);
		    bundle.putString("questionName", questionName);
		    bundle.putString("vote1", vote1);
		    bundle.putString("vote2", vote2);
		    bundle.putString("vote3", vote3);
		    bundle.putString("choice1", choice1);
		    bundle.putString("choice2", choice2);
		    bundle.putString("choice3", choice3);
		    intent.putExtras(bundle);
		    startActivity(intent);	
        } else if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {
            // 切换Activity
            // Intent intent = new Intent(ViewSnsActivity.this, UpdateStatusActivity.class);
            // startActivity(intent);
//            Toast.makeText(this, "向右手势", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onDoubleTap(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onDoubleTapEvent(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onSingleTapConfirmed(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	public boolean onTouch(View v, MotionEvent event) {
		return mGestureDetector.onTouchEvent(event);
	}
	
}
